package cn.ainit.sys.query;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Date;

import javax.activation.DataSource;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Intercepter;

import cn.ainit.sys.constant.SystemConstant;
import cn.ainit.sys.ds.store.sysDataStore;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryJson;
import cn.ainit.sys.query.entity.QueryTheMainList;
import cn.ainit.test.web.User;

/****
 * 查询界面
 * @author xuzq
 *
 * 封装select
 *
 * 最终实现：
 * 		独立查询界面：1.全部条件输入表单   2.页面按钮
 * 		跳转到查询界面：1.部分条件录入框    2.查询界面按钮 3.data grid [column、data]
 * 
 */

@Controller
@RequestMapping("/query")
public class DynamicQueryController {
	
	DynamicQueryService dynamicQueryService;
	
	@Resource
	public void setDynamicQueryService(DynamicQueryService dynamicQueryService) {
		this.dynamicQueryService = dynamicQueryService;
	}
	
	@RequestMapping("/multiquery")
	public String multiQuery(String formId,HttpServletRequest request){
		//查找按钮  跳转到界面
		request.setAttribute("formId", formId);
		return "/homepages/query/qallcol";
	}
	
	@RequestMapping("/querymainlist")
	@ResponseBody
	public QueryTheMainList getQueryTheMainList(String formId,HttpServletRequest reques){
		QueryTheMainList queryTheMainList = new QueryTheMainList();
		try {
			// 获取部分查询框   获取按钮    获取显示字段   （根据传入的参数是否取数据 ）
//			queryTheMainList.setQueryColumns(dynamicQueryService.getQueryColumns(partOrAll));
			queryTheMainList.setQueryColumns(dynamicQueryService.getQueryColumns(SystemConstant.QUERY_FIRST,formId));
			queryTheMainList.setQueryButtons(dynamicQueryService.getQueryButtons(SystemConstant.QUERY_FIRST,formId));
			QueryJson queryJson = new QueryJson();
			String flag = "";//Extend Config Flag
			queryJson.setColumns(dynamicQueryService.getQueryShowColumns(flag,formId));
			queryTheMainList.setQueryJson(queryJson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryTheMainList;
	}
	
	//实现select 查询结果
	//  querySelect  
	@RequestMapping("/querySql")
	@ResponseBody
	public QueryJson querySql(String conditionSql,String formId,QueryJson queryJson,HttpServletRequest reques) throws Exception{
		//1.先根据formId查询sql   2.然后将sql和conditionSql拼接   3.用sql去查询数据 返回前台
		if (queryJson == null) {
			queryJson = new QueryJson();
		}
		try {
			DataStore dataStore = dynamicQueryService.querySql(formId);
			String sql =dataStore.getSqlText();
			sql += conditionSql == null?"":conditionSql;
			queryJson.setTablePK(dataStore.getTablePK());
			queryJson.setRows(dynamicQueryService.getRows(sql,queryJson.getPageNumber(),queryJson.getPageSize()));
			System.out.println(queryJson.getRows());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}
	
	//添加DS_SQL
	@RequestMapping("/saveDS_SQL")
	@ResponseBody
	public int saveDS_SQL(sysDataStore dataStore,HttpServletRequest reques) throws Exception{
		
		//添加
		try {
//			dataStore.setUpdateTable("t_user");
			dynamicQueryService.addDataStore(dataStore);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 2;
	}
	
	public static void main(String[] args) {
		try {
			User user = new User();
			user.setUserName("Shanghai");
			user.setAge("21");
			System.out.println(reflectTest(user));
 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	public static String reflectTest(Object model) throws Exception{
		try {
			String conditionSql ="where 1=1";
			//获取实体类的所有属性，返回Field数组
			Field[] field = model.getClass().getDeclaredFields();
		
			//遍历所有属性
			 for (int i = 0; i < field.length; i++) {  
				 String name = field[i].getName();
				 //将属性的首字母大写，方便构造get，set
				 name = name.substring(0, 1).toUpperCase() + name.substring(1);  
				 //获取属性的类型
				 String type = field[i].getGenericType().toString();
				 if (type.equals("class java.lang.String")) {  
					 Method m = model.getClass().getMethod("get" + name); 
					 String value = (String) m.invoke(model);
					 if(value != null){
						 conditionSql +=" and "+name+"= '"+value+"'";
					 }else{
						 System.out.println(name+"="+value);
					 }
				 }
				 if (type.equals("class java.lang.Integer")) {  
                     Method m = model.getClass().getMethod("get" + name);  
                     Integer value = (Integer) m.invoke(model);  
                     if(value != null){
						 conditionSql +=" and"+name+"="+value;
					 }else{
						 System.out.println(name+"="+value);
					 }
				 }
				 if (type.equals("class java.lang.Double")) {  
                     Method m = model.getClass().getMethod("get" + name);  
                     Double value = (Double) m.invoke(model);  
                     if(value != null){
						 conditionSql +=" and"+name+"="+value;
					 }else{
						 System.out.println(name+"="+value);
					 }
				 }
				 if (type.equals("class java.util.Date")) {  
                     Method m = model.getClass().getMethod("get" + name);  
                     Date value = (Date) m.invoke(model);  
                     if(value != null){
						 conditionSql +=" and"+name+"="+value;
					 }else{
						 System.out.println(name+"="+value);
					 }
				 }
			 }
			 return conditionSql;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	 
}

